<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="数据源名称">
          <a-input placeholder="请输入..." v-decorator="['name', validatorRules.name]"/>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="sql语句">
          <a-textarea rows="4" placeholder="请输入sql语句" v-model="sqlcmd" v-decorator="['sqlcmd',validatorRules.sqlcmd ]"/>
        </a-form-item>
        <a-row style="margin-left: 13%;width:80%;">
          <a-col :lg="10">
            <a-form-item :labelCol="{ xs: {span: 20}, sm: {span: 7} }" :wrapperCol="wrapperCol" label="数据库">
              <a-select placeholder="请选择..." v-model="db">
                <a-select-option v-for="(dmap,index) in databaselist" :key="index" :value="dmap.value">{{ dmap.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="12">
            <a-form-item :labelCol="{ xs: {span: 24}, sm: {span: 8} }" :wrapperCol="wrapperCol" label="数据源编码">
              <a-input placeholder="请输入..." v-model="db_code" v-decorator="['code', validatorRules.code]"/>
            </a-form-item>

          </a-col>
        </a-row>
        <div :style="{ border:'1px solid #e8e8e8', marginTop:'10px',padding:'10px 24px',minHeight:'48px' }">
          <a-button @click="doAnalyseData" type="primary" icon="eye">解析数据</a-button>
        </div>
        <table class="owneTable">
          <tr class="th">
            <td class="tdOne">变量</td>
            <td class="tdtwo">默认值</td>
          </tr>
          <tr v-for="(value,i) in dataSource">
            <td class="tdOne">{{value.ikey}}</td>
            <td class="tdtwo">
              <a-input placeholder="请输入..." v-model="value.ivalue"/>
            </td>
          </tr>
        </table>
        <div :style="{ border:'1px solid #e8e8e8', marginTop:'10px',padding:'10px 24px',minHeight:'48px' }">
          <a-button @click="doPreviewData" type="primary" icon="eye">预览数据</a-button>
        </div>

        <!-- 数据预览区域tabs -->
        <a-tabs type="card">
          <a-tab-pane tab="HTML" key="1">
            <a-table :columns="columnshtml" :dataSource="data" style="overflow:scroll;height:250px;">
            </a-table>
          </a-tab-pane>
          <a-tab-pane tab="JSON" key="2">
            <textarea style="width:100%;font-size: 16px;font-weight:500" :rows="10" v-html="resultJson"
                      readonly></textarea>
          </a-tab-pane>
          <a-tab-pane tab="XML" key="3">
            <textarea style="width:100%;font-size: 16px;font-weight:500" :rows="10" v-html="resultXML"
                      readonly></textarea>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
    import {httpAction, getAction, postAction} from '@/api/manage'
    import pick from 'lodash.pick'
    import {JeecgListMixin} from '@/mixins/JeecgListMixin'

    export default {
        name: "TpDataSourceModal",
        mixins: [JeecgListMixin],
        data() {
            return {
                title: "操作",
                model: {},
                labelCol: {
                    xs: {span: 24},
                    sm: {span: 5},
                },
                wrapperCol: {
                    xs: {span: 24},
                    sm: {span: 16},
                },
                sqlcmd: "",
                resultJson: {},
                resultXML: {},
                resultHtml: {},
                data: [],
                columnshtml: [],
                visible: false,
                confirmLoading: false,
                form: this.$form.createForm(this),
                validatorRules: {
                    name: {rules: [{required: true, message: '请输入数据源名称!'}]},
                    sqlcmd: {rules: [{required: true, message: '请输入sql语句!'}]},
                    code: {rules: [{required: true, message: '请输入数据源编码!'}]},
                },
                dataSource: [],
                url: {
                    list: "/tpsoft/tpDataSource/list",
                    add: "/tpsoft/tpDataSource/add",
                    edit: "/tpsoft/tpDataSource/edit",
                    prieview: "tpsoft/tpDataSource/updateSql",
                    analyse: "/tpsoft/tpDataSource/getParamsAnalysis",
                    checkCode: "/tpsoft/tpDataSource/checkCode",
                    queryAllbase: "/sys/dict/getDictItems/dynamic_database",
                },
                databaselist:[],
                db:'',
                db_code:'',
            }
        },
        created() {
          this.queryDb();
        },
        methods: {
          queryDb(){
            let that = this;
            httpAction(that.url.queryAllbase,{},'get').then((res)=>{
              if(res.success){
                that.databaselist = res.result;
              }
            });
          },
            doPreviewData() {
                if (undefined == this.sqlcmd) {
                    this.$message.warning("请先输入正确的sql语句");
                    return;
                }
              if (undefined == this.db_code) {
                this.$message.warning("请先输入正确的编码");
                return;
              }
                const that = this;
                let httpurl = that.url.prieview;
                let method = 'post';
                let formData = [];
                that.dataSource.forEach(function (item) {
                    if (null == item.ivalue || "" == item.ivalue) {
                        /*that.$message.warning("请先输入正确的默认值");
                        return;*/
                    } else {
                        formData.push(item);
                    }
                });
                //if (formData.length == that.dataSource.length) {
                    let sqlData = {};
                    sqlData.ikey = "db_sql";
                    sqlData.ivalue = that.sqlcmd;
                    formData.push(sqlData);
                    let dbData = {};
                    dbData.ikey = "db_db";
                    dbData.ivalue = that.db;
                    formData.push(dbData);
                    let codeData = {};
                    codeData.ikey = "db_code";
                    codeData.ivalue = that.db_code;
                    formData.push(codeData);
                    // 发起请求
                    //alert(JSON.stringify(formData))
                    httpAction(httpurl, formData, method).then((res) => {
                        if (res.success) {
                            that.resultJson = res.result.jsonArray;
                            that.resultXML = res.result.xmlStr;
                            that.columnshtml = res.result.columnsArray;
                            that.data = res.result.jsonArray;
                            that.$message.success(res.message);
                        } else {
                            that.$message.warning(res.message);
                        }
                    }).finally(() => {
                        /*that.close();*/
                    })
                /*}else{

                }*/
            },
            doAnalyseData() {
                if (undefined == this.sqlcmd) {
                    this.$message.warning("请先输入正确的sql语句");
                    return;
                }
                let requestP = {};
                const that = this;
                requestP.sql = that.sqlcmd;
                postAction(that.url.analyse, requestP).then(res => {
                    if (res.success) {
                        let dataList = [];
                        for (let i = 0; i < res.result.length; i++) {
                            let dataMap = {};
                            dataMap.ikey = res.result[i].ikey;
                            dataMap.ivalue = res.result[i].ivalue;
                            dataList.push(dataMap);
                        }
                        that.dataSource = dataList;
                        that.$message.success(res.message);
                    } else {
                        that.$message.warning(res.message);
                    }
                }).catch(err => {
                    that.$message.warning("接口异常，请尝试刷新");
                });
            },
            add() {
                this.edit({});
            },
            edit(record) {
                this.form.resetFields();
                this.model = Object.assign({}, record);
                this.visible = true;
                if (this.model != null && this.model.sqlcmd != "") {
                    this.sqlcmd = this.model.sqlcmd;
                }
                if (this.model != null && this.model.db != "") {
                  this.db = this.model.db;
                }
                this.$nextTick(() => {
                    this.form.setFieldsValue(pick(this.model, 'name', 'sqlcmd', 'code','db'))
                    //时间格式化
                });

            },
            close() {
                this.$emit('close');
                this.visible = false;
                this.sqlcmd = "";
                this.dataSource = [];
                this.resultJson = {};
                this.resultXML = {};
                this.resultHtml = {};
                this.data = [];
                this.columnshtml = [];
            },
            handleOk() {
                const that = this;
                // 触发表单验证
                this.form.validateFields((err, values) => {
                    if (!err) {
                        that.confirmLoading = true;
                        let httpurl = '';
                        let method = '';
                        let checkform = {};
                        let formData = Object.assign(that.model, values);
                        if (!formData.id) {
                            httpurl += that.url.add;
                            method = 'post';
                            checkform.type = "add";
                            checkform.code = formData.code;
                        } else {
                            httpurl += that.url.edit;
                            method = 'put';
                            checkform.type = "edit";
                            checkform.code = formData.code;
                            checkform.id = formData.id;
                        }
                        //alert(JSON.stringify(checkform))
                        httpAction(that.url.checkCode, checkform, 'post').then((res) => {
                            if (!res.result) {
                                that.$message.warning(res.message);
                                that.confirmLoading = false;
                                return;
                            } else {
                                console.log(formData)
                                formData.db = that.db;
                                // alert(JSON.stringify(formData))
                                httpAction(httpurl, formData, method).then((res) => {
                                    if (res.success) {
                                        that.$message.success(res.message);
                                        that.$emit('ok');
                                    } else {
                                        that.$message.warning(res.message);
                                    }
                                }).finally(() => {
                                    that.confirmLoading = false;
                                    that.close();
                                })
                            }
                        })
                    }
                })
            },
            handleCancel() {
                this.close()
            },


        }
    }
</script>

<style lang="less" scoped>
  .owneTable {
    width: 100%;
    font-family: "Chinese Quote", -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
    font-size: 14px;
    font-variant: tabular-nums;
    line-height: 1.5;
    color: rgba(0, 0, 0, 0.65);
    box-sizing: border-box;
    margin: 0;
    margin-top: 20px;
    padding: 0;
    list-style: none;
    position: relative;
    clear: both;

    .th {
      background: #f6f6f6;

      tr {
        td {
          padding: 12px 8px;
          border: 1px solid #e8e8e8;
        }

        .tdone {
          width: 40%;
        }
      }
    }

    tr {
      td {
        padding: 12px 8px;
        border: 1px solid #e8e8e8;
      }

      .tdtwo {
        width: 60%;
      }
    }
  }
</style>